package com.mls.guardian.executor.master;

import com.mls.guardian.container.MasterContainer;
import com.mls.guardian.dataobj.FileObj;
import com.mls.guardian.dataobj.ServerProcessInfo;
import com.mls.guardian.protocol.RemoteBody;
import com.mls.guardian.protocol.RemoteCommand;
import com.mls.guardian.protocol.body.FileInfoBody;
import com.mls.guardian.protocol.body.ServerProcessInfoBody;
import com.mls.guardian.remoting.executor.RemoteExecutor;
import io.netty.channel.ChannelHandlerContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * Created by 2014-400 on 2015-11-30.
 */
public class GetFileInfoExecutor implements RemoteExecutor {
    private static final Logger log = LoggerFactory.getLogger(GetFileInfoExecutor.class);
    private MasterContainer container;

    public GetFileInfoExecutor(MasterContainer container) {
        this.container = container;
    }


    @Override
    public RemoteBody execute(ChannelHandlerContext ctx, RemoteCommand request) throws Exception {
        FileInfoBody fileInfoBody = (FileInfoBody) request.getRemoteBody();

        Map clients = container.getClientDispatch().getClient();
        List<String> listAddr = new ArrayList<String>();
        Iterator iterator = clients.keySet().iterator();
        while (iterator.hasNext()) {
            listAddr.add((String) iterator.next());
        }

        //一次只能操作一台机器的一个应用
        log.info("----开始GetFileInfo[{}],[{}],[{}],[{}]---", fileInfoBody.getIpAddress(), fileInfoBody.getProjectName(), fileInfoBody.getModuleName(), fileInfoBody.getParent());
        if (listAddr.contains(fileInfoBody.getIpAddress())) {
            //SLAVE
            List<String> listClient = new ArrayList<String>();
            listClient.add(fileInfoBody.getIpAddress());

            List<RemoteBody> remoteBodyList = container.getClientDispatch().sendRequestToClients(request, listClient, -1);
            FileInfoBody body = (FileInfoBody) remoteBodyList.get(0);

            log.info("----结束slave[{}]-[{}]---", body.isSuc(), body.getChildren() == null ? -1 : body.getChildren().size());
            if (!body.isSuc()) {
                fileInfoBody.setSuc(false);
                fileInfoBody.setErrorContent(body.getErrorContent());
                return fileInfoBody;
            }

            fileInfoBody.setSuc(true);
            fileInfoBody.setChildren(body.getChildren());
        } else {
            //MASTER
            List<FileObj> fileObjList = container.getAppController().getFileInfo(fileInfoBody.getProjectName(), fileInfoBody.getModuleName(), fileInfoBody.getParent());

            log.info("----结束master[{}]---", fileObjList == null ? -1 : fileObjList.size());
            fileInfoBody.setSuc(true);
            fileInfoBody.setChildren(fileObjList);
        }

        return fileInfoBody;
    }
}
